const axios = require('axios');
const cheerio = require('cheerio');
const mysql = require('mysql');

// 页面
const page = 1;

// 配置数据库对象
let options = {
    // 数据库ip
    host:'192.168.88.211',
    // 端口号
    port:'3306',
    // 用户名
    user:'root',
    // 连接密码
    password:'123456',
    // 要连接的数据库
    database:'books'
}

// 实例化数据库
let con = mysql.createConnection(options);

// 链接数据库
con.connect((err)=>{
    if (err) {
        console.log(err);
    } else {
        console.log('连接数据库成功！！！');
    }
})

// 页面函数
const getPageUrl = async (num)=>{
    let httpUrl = 'https://sobooks.cc/page/' + num;
    let res = await axios.get(httpUrl);

    // 把我们拿到的页面数据丢进cheerio中
    const $ = cheerio.load(res.data);

    $('#cardslist .thumb-img>a').each((i , ele)=>{
        let href = $(ele).attr('href')
        getBookInfo(href);
    }) 
    
}

// 书籍详情页面
const getBookInfo = async (href)=>{
    let res = await axios.get(href);
    const $ = cheerio.load(res.data);
    // 书籍图片
    let bookimg = $('#article-content .item .bookpic>img').attr('src');
    // 书籍名称 
    let bookname = $('#article-content .item .bookinfo li:nth-child(1)').text();
    bookname = bookname.substring(3,bookname.length);
    
    // 书籍作者
    let author = $('#article-content .item .bookinfo li:nth-child(2)').text();
    author = author.substring(3 , author.length);

    // 书籍分类
    let viewcount = $('#article-content .item .bookinfo li:nth-child(3)').text();
    viewcount = viewcount.substring(3 , viewcount.length-1);
    // 书籍时间
    let tag = $('#article-content .item .bookinfo li:nth-child(5)').text();
    tag = tag.substring(3 , tag.length);
    // 书籍评分
    let score = $('#article-content .item .bookinfo li:nth-child(6)>b').attr("class");
    score = score[score.length-1];
    
    // 出版社
    let pubcompary = $('#article-content .item .bookinfo li:nth-child(7)').text();
    pubcompary = pubcompary.substring(5 , pubcompary.length);
    // 书籍链接
    let bookUrl = href;
    let arrBook = [bookname,author,viewcount,tag,score,pubcompary,bookimg,bookUrl];
    
    // 插入数据
    let strSql = 'INSERT INTO jianjie (bookname,author,viewcount,tag,score,pubcompary,bookimg,bookUrl) VALUES (?,?,?,?,?,?,?,?);'
    // 插入数据
    con.query(strSql , arrBook , (err , results)=>{
        console.log(err);
        console.log(results);
    })

}

getPageUrl(page);

// 关闭连接
// con.end();
